import cgi
import csv
import logging
import string


from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from urlparse import urlparse
import random
from django.utils import simplejson  


class UserInfo(db.Model):
    uid = db.IntegerProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    user = db.UserProperty()
    name = db.StringProperty()
    email = db.EmailProperty()
    token = db.StringProperty()
    

class Sessions(db.Model):
    date = db.DateTimeProperty(auto_now_add=True)
    gid = db.StringProperty()
    fname = db.StringProperty()
    owner = db.UserProperty()
    email = db.EmailProperty()
    data = db.BlobProperty()
    

class User(webapp.RequestHandler):
    def get(self):
      pass



class LoadFile(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user is None:
            self.response.out.write('Please Login')
            return
        logging.debug("email=%s" % user.email())

        fname = self.request.get('name')

        obj = {}
        data = []
        #load list from db
        try:
            res = db.GqlQuery("SELECT * FROM Sessions WHERE email = :1 AND fname = :2", user.email(), fname)
            obj['msg'] = "Success"
            for r in res:
                data.append(r.data)
        except:
            data = []
            obj['msg'] = "Fail"

        obj['data'] = data
        jsonstr = simplejson.dumps(obj)
        self.response.out.write(jsonstr) 


class Load(webapp.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user is None:
            self.response.out.write('Please Login')
            return
        logging.debug("email=%s" % user.email())

        obj = {}
        data = []
        #load list from db
        try:
            res = db.GqlQuery("SELECT * FROM Sessions WHERE email = :1", user.email())

            obj['msg'] = "Success"
            for r in res:
                #self.response.out.write('r=%s<br>' % (r.fname))
                session = {}
                tmp = string.split(str(r.date), ".")
                session['date'] = tmp[0]
                session['name'] = r.fname
                data.append(session)
        except:
            data = []
            obj['msg'] = "Fail"

        obj['data'] = data
        jsonstr = simplejson.dumps(obj)
        self.response.out.write(jsonstr) 


class Save(webapp.RequestHandler):
    def post(self):
        user = users.get_current_user()
        if user is None:
            self.response.out.write('Please Login')
            return

        json_arr = {}
        json_arr = simplejson.loads(self.request.body)

        #logging.debug("json_arr=%s" % json_arr)

        #save in the db
        q = db.GqlQuery("SELECT * FROM Sessions WHERE gid = :1 AND fname = :2", str(json_arr['gid']), json_arr['name'])
        r = q.fetch(1)

        if len(r) == 1:
            session = r[0]
            logging.debug("found existing session file=%s" % session.fname)
        else:
            session = Sessions()

        session.owner = user
        session.gid = str(json_arr['gid'])
        session.email = user.email()
        session.fname = json_arr['name']
        session.data = db.Blob(self.request.body)

        session.put()

    def get(self):
        pass


application = webapp.WSGIApplication(
                                 [('/save', Save), ('/load', Load), ('/loadfile', LoadFile)],
                                 debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
